'use strict'

/**
 * 此模块对模型的初始化主要为cmd目录下的命令提供。
 */

const config = require('../config/config.js')

const {initORM} = require('psqlorm')

const fs = require('fs')

let dbconfig = {...config.dbconfig}

dbconfig.max = 2

let pqorm = initORM(dbconfig, config.dbschema)

pqorm.setSchema(config.dbschema)

let model_files = []

let path = __dirname + '/../model'

let files = fs.readdirSync(path, {withFileTypes: true})
let model
let m
let db = {}

for (let f of files) {
  if (!f.isFile() || f.name[0] === '!' || f.name[0] === '_') continue

  if (f.name.substring(f.name.length-3) !== '.js') continue

  try {
    model = require(`${path}/${f.name}`)
    if (model.__proto__.name === 'PostgreModel') {
      m = new model(pqorm)
      db[ f.name.substring(0, f.name.length-3) ] = m
    }
  } catch (err) {
    console.error(err)
  }

}

db.end = () => {
  pqorm.end()
}

db._pqorm = pqorm

module.exports = db
